﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace library
{
    class p2pRequestHeader
    {
        internal RequestCommand Command = RequestCommand.Data;

        internal Peer Peer;

        internal p2pRequestHeader(RequestCommand command = RequestCommand.Data, Peer peer = null)
        {
            Command = command;

            Peer = peer;
        }

        internal p2pRequestHeader(byte[] parameters)
        {
            Command = (RequestCommand)parameters[0];

            IPEndPoint endPoint = Addresses.FromBytes(parameters.Skip(Parameters.requestHeaderParamsSize).ToArray());

            if(endPoint != null)
                Peer = Peers.GetPeerOrCreate(endPoint);
        }

        static byte[] ToBytes(RequestCommand command)
        {
            byte[] b = new byte[Parameters.requestHeaderSize];

            b[0] = (byte)command;

            return b;
        }

        internal IEnumerable<byte> ToBytes()
        {
            byte[] b = ToBytes(Command);

            if (Peer != null)
                Addresses.ToBytes(Peer.EndPoint).CopyTo(b, Parameters.requestHeaderParamsSize);

            return b;
        }
    }

    enum RequestCommand
    {
        None = 0,
        Data = 1,
        Metadata = 2,
        Peer = 3
    }
}
